<?php


namespace app\admin\controller;


use app\admin\model\Admin;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Model;
use think\response\Json;

class AgentrobotLivestreamerList extends Backend
{
    /**
     * LiveStreamer模型对象
     */
    protected $model = null;
    protected $admin = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\AgentrobotLivestreamerList();

        $this->admin = new Admin();
    }

    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {

            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->username] = $value->username;
            }

//            select robotuser from rubotuser_list where robotType =1 and agentID = 当前经纪人
            $robotUser = db('robotuser_list')->where([
                "robotType" => 2,
                "agentID" => $this->auth->username
            ])->select();
            $robotUserList = [];
            foreach ($robotUser as $v) {
                $robotUserList[$v['robotUser']] = $v['robotUser'];
            }
            $this->assignconfig("grade", [
                ['id' => "-1", "name" => '未知'],
                ['id' => "0", "name" => '放弃'],
                ['id' => "1", "name" => '一般'],
                ['id' => "2", "name" => '优质'],
            ]);
            $this->assignconfig("checkStatus", [
                ['id' => "-1", "name" => '未知'],
                ['id' => "0", "name" => '不可签约'],
                ['id' => "1", "name" => '可签约'],
            ]);
            $this->assignconfig("robotUser", $robotUserList);
            $this->assignconfig("adminUserList", $list);
            $this->assign("loginUsername", $this->auth->username);
            $this->assign("loginUserId", $this->auth->username);

            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $where = json_decode($this->request->get("filter", ''), true);
//print_r($where);
        if (isset($where['followTime']) && $where['followTime'] > 0) {
            if ($where['followTime'] == '1') {
                $where["followTime"] = ["egt", date("Y-m-d", strtotime("-7 days"))];
            } elseif ($where['followTime'] == '2') {
                $where["followTime"] = ["egt", date("Y-m-d", strtotime("-14 days"))];
            } elseif ($where['followTime'] == '3') {
                $where["followTime"] = ["egt", date("Y-m-d", strtotime("-30 days"))];
            } elseif ($where['followTime'] == '4') {
                $where["followTime"] = ["egt", date("Y-m-d", strtotime("-90 days"))];
            }
        }

        $list = $this->model
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
//echo $this->model->getLastSql();die;
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function follow($ids)
    {
        if (false === $this->request->isPost()) {
            $data = db("livestreamer_list")->where([
                'livestreamerUser' => $ids
            ])->find();

            $this->assign("userInfo", $data);
            $this->assign("id", $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            $sql = "CALL `livestreamer_memo` (";
            $sql .= "'" . $params["id"] . "', '" . $params['content'] . "', @_res)";
            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function sign($ids)
    {
        if (false === $this->request->isPost()) {
            $admin = $this->admin->where([
                'status' => 'normal'
            ])->select();

            $list = [];
            foreach ($admin as $item => $value) {
                $list[$value->id] = $value->username;
            }
            $this->assign("agentstaffList", $list);
            $this->assign("loginUserId", $this->auth->id);
            $this->assign("id", $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if (!$params['livestreamerUser'] || !$params["agentID"] || !$params['phoneNumber']) {
            $this->error("参数有误");
        }

        $result = false;
        Db::startTrans();
        try {
            $sql = "call livestreamer_sign (";
            $sql .= "'".$params['livestreamerUser']."', '" . $params["agentID"] . "', '".$params['phoneNumber']."', @_res)";

            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    public function finduser()
    {
        $user = $this->request->get("user");

        $data = db('livestreamer_list')->where([
            'livestreamerUser' => $user
        ])->find();

        return json($data);
    }


    public function recheck($ids)
    {
        $result = false;
        Db::startTrans();
        try {

            $sql = "call livestreamer_recheck('".$ids."', @_res)";
            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success();
    }

    public function discard($ids)
    {
        $result = false;
        Db::startTrans();
        try {
            $data = db("view_agentrobot_livestreamer_list")->where([
                'livestreamerUser' => $ids
            ])->find();

            $sql = "call livestreamer_discard('".$ids."', '".$data['agentID']."', @_res)";
            Db::query($sql);
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error("操作失败");
        }
        $this->success();
    }
}